package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

//数据库工具类
public class DBUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //静态代码块只能执行一次
    static {
        InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
        //创建一个properties对象
        Properties properties = new Properties();
        try {
            //properties
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    static {
        try {
            //加载驱动类
            Class.forName("oracle.jdbc.OracleDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //创建连接
    public static Connection getConnection() throws ClassNotFoundException, SQLException {


        //创建连接

        return DriverManager.getConnection(url,username,password);
    }

    //关闭资源
    public static void close(AutoCloseable...closeables){
        for (AutoCloseable closeable : closeables) {
            if (closeable!=null){
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
